<html>
  <head>
    <title>Calculator</title>
  </head>
  <body>
    <h1>Calculator</h1>
    <p>
    (Ver 1.1 4/9/2012 by Chris Moghbel)<br />
    Type an expression in the following box (e.g., 10.5+20*3/25)
    </p>
    <form method="GET">
      <input type="text" name="exp">
      <input type="submit" value="Calculate">
    </form>
    <ul>
      <li>Only numbers and +,-,*, and / operators are allowed in the expression.</li>
      <li>The evaluation follows the standard operator precedence.</li>
      <li>The calculator does not support parentheses.</li>
      <li>The calculator handles invalid input "gracefully". It does not output PHP error messages.</li>
    </ul>
    <?php
      if ($_GET['exp']) {
        $expr = $_GET['exp'];
        echo "<h2>Result</h2>";
        if (checkExpression($expr)) {
          $result = evalExpression($expr);
          echo $expr." = ".$result;
        }
      }
    ?> 
  </body>

  <?php
    function checkExpression($expr) {
      if (preg_match("/[^\d+-\/*]/", $expr) == 1) {
        echo "Invalid input expression $expr.";
        return false;
      }
      return true;
    }

    function evalExpression($expr) {
      $result = '';
      try {
        @eval("\$result=$expr;");
      }
      catch (Exception $E) {
        # Do Nothing.
      }
      return $result;
    }
  ?>
</html>
